package com.cp.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.cp.base.util.JwtUtils;
import com.cp.common.result.R;
import com.cp.core.hfb.RequestHelper;
import com.cp.core.pojo.vo.UserBindVO;
import com.cp.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author ming
 * @since 2022-07-27
 */
@Api(tags = "会员账号绑定")
@Slf4j
@RestController
@RequestMapping("/api/core/userBind")
public class UserBindController {
   @Resource
   private UserBindService userBindService;
   @ApiOperation("账户绑定提交数据")
   @PostMapping("/auth/bind")
   public R bind(@RequestBody UserBindVO userBindVO, HttpServletRequest request){
       //确保用户已经登录 从header中获取token 并对token进行校验,从token获取userId
       String token = request.getHeader("token");
       Long userId = JwtUtils.getUserId(token);
       //根据userId做账户绑定,生成一个动态表单的字符串
       String fromStr = userBindService.commitBindUser(userBindVO,userId);
       return R.ok().data("formStr",fromStr);
   }
   @ApiOperation("账户绑定异步回调必须给fhb返回success")
   @PostMapping("/notify")
   public String notify(HttpServletRequest request){
       Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
       log.info("账户绑定异步回调接收的参数如下{}", JSON.toJSONString(paramMap));
       //验签
       if (!RequestHelper.isSignEquals(paramMap)) {
           log.error("用户签名验证失败:{}",JSON.toJSONString(paramMap));
           return "fail";
       }
       log.info("验签成功!开始账号绑定");
       userBindService.notify(paramMap);
       return "success";
   }
}

